/*
 * 
 * ******Capture Main Activity***********************
 ******* 1)Sync Word details to server***************
 ******* 2)Sync Phrase details to server*************
 ******* 3)Sync Songs details to server**************
 ******* 4)Sync Story details to server**************
 ******* 5)Sync Idiom details to server**************
 ****************************************************/

package com.maori.languageapp;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
//import com.maori.languageapp.adapter.LanguageAppDialetDataList;
import com.maori.languageapp.adapter.Maori_NavDrawerListAdapter;
import com.maori.languageapp.consts.CaptureFilterAdapter;
import com.maori.languageapp.consts.UrlContant;
//import com.maori.languageapp.discover.Maori_Discover_Word_Details;
import com.maori.languageapp.fragments.Maori_Main_Fragment;
import com.maori.languageapp.model.Maori_NavDrawerItem;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class LanguageAppCaptureModify extends FragmentActivity implements
OnClickListener {
	Camera camera;
	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	HttpParams httpParameters = new BasicHttpParams();
	int timeoutConnection = 5000;
	int NCMID;
	String CATEGORYID;
	String node_category, CurrentCategory, node_category_id;
	String type;
	public FTPClient mFTPClient = null;
	// Capture Word Data Insert Block
	EditText etmaoriword, etenglishword, searchfiltertext;
	// Capture Story Data Insert Block
	EditText etmaoristorytitle, etmaoristorycontent, etenglishstorytitle,
			etenglishstorycontent;
	// Capture Songs Data Insert Block
	EditText etmaorisongstitle, etmaorisongscontent, etenglishsongstitle,
			etenglishsongscontent;
	// Capture Phrase Data Insert Block
	EditText etmaoriphrase, etenglishphrase;
	// Capture Idiom Data Insert Block
	EditText etmaoriidiom, etenglishidiom;
	// Common Data insert block
	EditText etvideourl;
	private Uri fileUri;
	Button record_button, play_button, camera_button, gallery_button,
			audio_gallery_button, video_gallery_button, submitbtn, cancelbtn,
			videorecord_button, videorecordplay_button, btnsearchstart,
			btnsearchclose;
	String CurrentUID, CurrentUserName;
	InputStream is = null;
	StringBuilder sb = null;
	String result = null;
	String SEARCHKEY, ACTIVE;
	private MediaRecorder myRecorder;
	int recordActive = 0;
	int recordPlay = 0;
	int recordPlayVideo = 0;
	String CurrentContentType = "0";
	private MediaPlayer myPlayer;
	private String outputFile = null;
	ImageView ivThumbnailPhoto;
	ListView rdgrp;
	TextView screenTitle;
	private CaptureFilterAdapter dbHelper;
	private SimpleCursorAdapter dataAdapter;
	String UpdatingNodeID; // NodeID
	ArrayList<HashMap<String, String>> arraylist;
	JSONArray jsonarray;
	// Camera Capture Action Constants
	// Data uploading
	String desDirectory = "http://langapp.mirzabros.com/lanappimage/";
	
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;

	private static final int SELECT_IMAGE = 1;
	private static final int SELECT_AUDIO = 2;
	private static final int SELECT_VIDEO = 3;
	String selectedPath = "";

	final static int REQUEST_VIDEO_CAPTURED = 3000;
	// Uri uriVideo = null;
	// directory name to store captured images and videos
	private static final String IMAGE_DIRECTORY_NAME = "lANGUAGEAPP";

	// ---------------------------------------------------
	VideoView videoPreview;
	int dialectidhere;
	Bitmap bitMap;

	// private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private ArrayList<Maori_NavDrawerItem> navDrawerItems;
	private Maori_NavDrawerListAdapter adapter;
	String CurrentTypeOfCapture, content_type_id;
	private Spinner spinnerTypeOfCapture, spinnerCategory;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerTC;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerCat;
	private static final int PICK_IMAGE = 1;
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	protected static final String TAG = null;
	// Master Tables
	private String USER_TABLE = "User";
	private String CONTENTTYPE_TABLE = "Content_type";
	private String DIALACT_TABLE = "Dialact";
	private String LANGUAGE_TABLE = "Language";
	private String MEDIA_TABLE = "Media";
	private String NODECATEGORY_TABLE = "Node_Category";
	private String PHRASE_TABLE = "Phrase";
	private String SONG_TABLE = "Song";
	private String STORY_TABLE = "Story";
	private String WORD_TABLE = "Word";
	private String IDIOM_TABLE = "Idiom";
	// Save Image,Audio Video Paths
	private String MEDIA_FILE_URL = "MediaFileUrl";

	private SQLiteDatabase mydb;
	int DialetPasition;
	private RadioButton listRadioButton = null;
	int listIndex = -1;
	private ListView listView;
	// private List<LanguageAppDialetDataList> rowItems;
	// LanguageAppDialetDataList DialetListData;
	// LanguageAppDialetAdapterList DialectAdapter;
	private static int RESULT_LOAD_IMAGE = 1;
	Uri selectedImageUri;
	byte[] data;
	String filemanagerstring;
	String selectedImagePath;
	String filePath;
	private Bitmap bitmap;
	LinearLayout capturewordblock, capturestoryblock, capturesongsblock,
			capturephraseblock, captureidiomblock, dmstloadmaindetails,
			searchlistresult, camvideoparent;
	private String tempDir;
	String currentAudioName = "202";
	String currentVideoName = "303";
	static String filename = "404";
	String saveWordDetailsUrl, savePhraseDetailsUrl, saveStoryDetailsUrl,
			saveIdiomDetailsUrl, saveSongDetailsUrl;
	static String sourceUrl;

	static String upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
	static String upladingFromPathGallery = "606";
	String upladingFromPathAudio = "/storage/emulated/0/";
	String upladingFromPathVideo = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
	private String servernameimages = "ftp.langapp.testarea.co.nz";
	private String servusername = "images@langapp.testarea.co.nz";
	private String passworsd = "languageapp@237";
	private int portnum = 21;

	ListView listViewitemslist;

	// Media resource path
	String AudioMainPath;
	
	RadioGroup rgOpinion;
	
	String SelectedDialect  = "1";

	public void btnBackAction(View view) {
		LanguageAppCaptureModify.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}

	public void onBackPressed() {
		super.onBackPressed();
		LanguageAppCaptureModify.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.language_app_capture_activity);
		// PSJ - Code To Add Drawer

		getCurrentUserDetails();
		dbHelper = new CaptureFilterAdapter(this);
		dbHelper.open();
		// Capture Web service Call Defines
		saveWordDetailsUrl = UrlContant.SaveModifyWordUrl;
		savePhraseDetailsUrl = UrlContant.SavePhraseUrl;
		saveStoryDetailsUrl = UrlContant.SaveStoryUrl;
		saveIdiomDetailsUrl = UrlContant.SaveIdiomUrl;
		saveSongDetailsUrl = UrlContant.SaveSongUrl;

		listViewitemslist = (ListView) findViewById(R.id.listViewitemslist);

		/**************************************************************************
		 * *******Search Excisting Filter Option*************
		 * ************************************************************************/
		btnsearchstart = (Button) findViewById(R.id.btnsearchstart);
		screenTitle = (TextView) findViewById(R.id.screenTitle);
		screenTitle.setText("Capture Modify Details");
		dmstloadmaindetails = (LinearLayout) findViewById(R.id.dmstloadmaindetails);
		searchlistresult = (LinearLayout) findViewById(R.id.searchlistresult);
		camvideoparent = (LinearLayout) findViewById(R.id.camvideoparent);

		// Get Values From EditText Values(Word)
		etmaoriword = (EditText) findViewById(R.id.etmaoriword);
		etenglishword = (EditText) findViewById(R.id.etenglishword);
		// Get Values From EditText Values(Story)
		etmaoristorytitle = (EditText) findViewById(R.id.etmaoristorytitle);
		etmaoristorycontent = (EditText) findViewById(R.id.etmaoristorycontent);
		etenglishstorytitle = (EditText) findViewById(R.id.etenglishstorytitle);
		etenglishstorycontent = (EditText) findViewById(R.id.etenglishstorycontent);
		searchfiltertext = (EditText) findViewById(R.id.searchfiltertext);

		// Get Values From EditText Values(Songs)
		etmaorisongstitle = (EditText) findViewById(R.id.etmaorisongstitle);
		etmaorisongscontent = (EditText) findViewById(R.id.etmaorisongscontent);
		etenglishsongstitle = (EditText) findViewById(R.id.etenglishsongstitle);
		etenglishsongscontent = (EditText) findViewById(R.id.etenglishsongscontent);
		// Get Values From EditText Values(Phrase)
		etmaoriphrase = (EditText) findViewById(R.id.etmaoriphrase);
		etenglishphrase = (EditText) findViewById(R.id.etenglishphrase);
		// Get Values From EditText Values(Idiom)
		etmaoriidiom = (EditText) findViewById(R.id.etmaoriidiom);
		etenglishidiom = (EditText) findViewById(R.id.etenglishidiom);

		etvideourl = (EditText) findViewById(R.id.etvideourl);

		// Button View Controllers
		record_button = (Button) findViewById(R.id.record_button);
		play_button = (Button) findViewById(R.id.play_button);
		camera_button = (Button) findViewById(R.id.camera_button);
		gallery_button = (Button) findViewById(R.id.gallery_button);
		audio_gallery_button = (Button) findViewById(R.id.audio_gallery_button);
		video_gallery_button = (Button) findViewById(R.id.video_gallery_button);
		videorecord_button = (Button) findViewById(R.id.videorecord_button);
		videorecordplay_button = (Button) findViewById(R.id.videorecordplay_button);
		videoPreview = (VideoView) findViewById(R.id.videoview);
		spinnerTypeOfCapture = (Spinner) findViewById(R.id.spinnerTypeOfCapture);
		spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
		rgOpinion = (RadioGroup) findViewById(R.id.radiodialet);
		btnsearchstart.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (type.equals("Word")) {
					Log.v(TAG, "****** Word *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("SEARCHKEY", searchfiltertext.getText()
							.toString());
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Word");
					startActivity(i);
				} else if (type.equals("Phrase")) {
					Log.v(TAG, "****** Phrase *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("SEARCHKEY", searchfiltertext.getText()
							.toString());
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Phrase");
					startActivity(i);

				} else if (type.equals("Story")) {
					Log.v(TAG, "****** Story *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("SEARCHKEY", searchfiltertext.getText()
							.toString());
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Story");
					startActivity(i);

				} else if (type.equals("Idiom")) {
					Log.v(TAG, "****** Idiom *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("SEARCHKEY", searchfiltertext.getText()
							.toString());
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Idiom");
					startActivity(i);

				} else if (type.equals("Song")) {
					Log.v(TAG, "****** Song *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("SEARCHKEY", searchfiltertext.getText()
							.toString());
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Song");
					startActivity(i);
				}
			}
		});

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			String NodeNCMID = extras.getString("NCMID");
			Log.e("PRINT 1:", ""+NodeNCMID);
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
			Cursor readUserDetails = null;
			try {
				String queryCheckUsers = "SELECT node_cat_id,node_category,NCMID FROM Node_Category Where NCMID = '" + NodeNCMID + "'";
				readUserDetails = mydb.rawQuery(queryCheckUsers, null);
			} catch (Exception e) {
				//node_cat_id text not null,node_category text not null,NCMID
			}
			if (readUserDetails != null) {
				if (readUserDetails.getCount() > 0) {
					while (readUserDetails.moveToNext()) {
						String node_cat_id = readUserDetails.getString(0);
						node_category = readUserDetails.getString(1);
						CATEGORYID = readUserDetails.getString(2);
						Log.e("PRINT 2:", node_category);
					}
				}
				else{
					Log.e("PRINT 3:", "Default");
					node_category = "Common";
				}
			}
			mydb.close();
			//node_category = extras.getString("node_category");
			type = extras.getString("type");
			SEARCHKEY = extras.getString("SEARCHKEY");
			// Check Excisting Items
			ACTIVE = extras.getString("ACTIVE");
			
			

			if (ACTIVE.equals("2")) {
				spinnerTypeOfCapture.setEnabled(false);
				spinnerCategory.setEnabled(false);
				etmaoriword.setEnabled(false);
				etenglishword.setEnabled(false);
				etmaoriphrase.setEnabled(false);
				etenglishphrase.setEnabled(false);
				etmaoriidiom.setEnabled(false);
				etenglishidiom.setEnabled(false);
				etmaoristorytitle.setEnabled(false);
				etenglishstorytitle.setEnabled(false);
				etmaoristorycontent.setEnabled(false);
				etenglishstorycontent.setEnabled(false);
				etmaorisongstitle.setEnabled(false);
				etmaorisongscontent.setEnabled(false);
				etenglishsongstitle.setEnabled(false);
				etenglishsongscontent.setEnabled(false);
			}

			Log.e(TAG, "******XXXX:" + ACTIVE);
			Log.e(TAG, "******XXXX:" + NCMID);
			Log.e(TAG, "******XXXX:" + node_category);
			Log.e(TAG, "******XXXX:" + type);
		}
		capturewordblock = (LinearLayout) findViewById(R.id.capturewordblock);
		capturestoryblock = (LinearLayout) findViewById(R.id.capturestoryblock);
		capturesongsblock = (LinearLayout) findViewById(R.id.capturesongsblock);
		capturephraseblock = (LinearLayout) findViewById(R.id.capturephraseblock);
		captureidiomblock = (LinearLayout) findViewById(R.id.captureidiomblock);
		// ****Define Main Type Capture Blocks****
		Log.v(TAG, "PRINT TYPE : " + type);
		// Sending RefID/MaoriTitle/EnglishTitle/MaoriContents/EnglishContent

		if (type.equals("Word")) {
			capturewordblock.setVisibility(LinearLayout.VISIBLE);
			String[] wordContents = SEARCHKEY.split("/");
			UpdatingNodeID = wordContents[0]; // Reference
			String MaoriContent = wordContents[3]; // Maori
			String EnglishContent = wordContents[4]; // English
			if (!MaoriContent.equals("00")) {
				etmaoriword.setText(MaoriContent);
				etenglishword.setText(EnglishContent);
			}

		} else if (type.equals("Phrase")) {
			capturephraseblock.setVisibility(LinearLayout.VISIBLE);
			String[] wordContents = SEARCHKEY.split("/");
			UpdatingNodeID = wordContents[0]; // Reference
			String MaoriContent = wordContents[3]; // Maori
			String EnglishContent = wordContents[4]; // English
			if (!MaoriContent.equals("00")) {
				etmaoriphrase.setText(MaoriContent);
				etenglishphrase.setText(EnglishContent);
			}
		} else if (type.equals("Story")) {
			capturestoryblock.setVisibility(LinearLayout.VISIBLE);
			String[] wordContents = SEARCHKEY.split("/");
			UpdatingNodeID = wordContents[0]; // Reference
			String MaoriTitle = wordContents[1]; // Maori
			String EnglishTitle = wordContents[2]; // English
			String MaoriContent = wordContents[3]; // Maori
			String EnglishContent = wordContents[4]; // English
			if (!MaoriContent.equals("00")) {
				etmaoristorytitle.setText(MaoriTitle);
				etenglishstorytitle.setText(EnglishTitle);
				etmaoristorycontent.setText(MaoriContent);
				etenglishstorycontent.setText(EnglishContent);
			}
		} else if (type.equals("Idiom")) {
			captureidiomblock.setVisibility(LinearLayout.VISIBLE);
			String[] wordContents = SEARCHKEY.split("/");
			UpdatingNodeID = wordContents[0]; // Reference
			String MaoriContent = wordContents[3]; // Maori
			String EnglishContent = wordContents[4]; // English
			if (!MaoriContent.equals("00")) {
				etmaoriidiom.setText(MaoriContent);
				etenglishidiom.setText(EnglishContent);
			}
		} else if (type.equals("Song")) {
			capturesongsblock.setVisibility(LinearLayout.VISIBLE);
			String[] wordContents = SEARCHKEY.split("/");
			UpdatingNodeID = wordContents[0]; // Reference
			String MaoriTitle = wordContents[1]; // Maori
			String EnglishTitle = wordContents[2]; // English
			String MaoriContent = wordContents[3]; // Maori
			String EnglishContent = wordContents[4]; // English
			if (!MaoriContent.equals("00")) {
				etmaorisongstitle.setText(MaoriTitle);
				etmaorisongscontent.setText(MaoriContent);
				etenglishsongstitle.setText(EnglishTitle);
				etenglishsongscontent.setText(EnglishContent);
			}
		}

		EditText EtType = (EditText) findViewById(R.id.ettypeofcapture);
		EditText EtCat = (EditText) findViewById(R.id.etselectcategory);

		// Submit Word Details To Server
		submitbtn = (Button) findViewById(R.id.submitbtn);
		submitbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// Get Selected Radio Button and display output
				RadioButton selectRadio = (RadioButton) findViewById(rgOpinion
						.getCheckedRadioButtonId());
				String SelectedOption = selectRadio.getText().toString();
				if (SelectedOption.equals("North Island")) {
					SelectedDialect  = "1";
				}
				else if(SelectedOption.equals("South Island")){
					SelectedDialect  = "2";
				}
				
				
				if (ACTIVE.equals("1")) {
					
					if (type.equals("Word")){
						if(etenglishword.getText().toString().trim().length() != 0 && etmaoriword.getText().toString().trim().length() != 0){
							new UploadingWordsDetails().execute();
						}
						else{
							showAlertDialog(LanguageAppCaptureModify.this,
									"INVALID DATA",
									"Please Enter Word Details...", false);
						}
					}
					
					else if (type.equals("Phrase")) {
						if(etenglishphrase.getText().toString().trim().length() != 0 && etmaoriphrase.getText().toString().trim().length() != 0){
									new UploadingWordsDetails().execute();
						}
						else{
							showAlertDialog(LanguageAppCaptureModify.this,
													"INVALID DATA",
													"Please Enter Phrase Details...", false);
							}
					}
					else if (type.equals("Idiom")) {
						if(etenglishidiom.getText().toString().trim().length() != 0 && etmaoriidiom.getText().toString().trim().length() != 0){
									new UploadingWordsDetails().execute();
						}
						else{
							showAlertDialog(LanguageAppCaptureModify.this,
													"INVALID DATA",
													"Please Enter Idiom Details...", false);
							}
					}
					else if (type.equals("Story")) {
						if(etenglishstorytitle.getText().toString().trim().length() != 0 && etmaoristorytitle.getText().toString().trim().length() != 0 && etenglishstorycontent.getText().toString().trim().length() != 0 && etmaoristorycontent.getText().toString().trim().length() != 0){
									new UploadingWordsDetails().execute();
						}
						else{
							showAlertDialog(LanguageAppCaptureModify.this,
													"INVALID DATA",
													"Please Enter Story Details...", false);
							}
					}
					else if (type.equals("Song")) {
						if(etenglishsongstitle.getText().toString().trim().length() != 0 && etmaorisongstitle.getText().toString().trim().length() != 0 && etenglishsongscontent.getText().toString().trim().length() != 0 && etmaorisongscontent.getText().toString().trim().length() != 0){
									new UploadingWordsDetails().execute();
						}
						else{
							showAlertDialog(LanguageAppCaptureModify.this,
													"INVALID DATA",
													"Please Enter Song Details...", false);
							}
					}
					//etenglishword    / etmaoriword
					
				} else if (ACTIVE.equals("2")) {

					new UploadingNodeMediaDetails().execute();
				
				}
				else if (ACTIVE.equals("3")) {

					
				
				}   
			}
		});
		
		
		

		// Cancel Current View and Exit
		cancelbtn = (Button) findViewById(R.id.cancelbtn);
		cancelbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				displayCancelDialog();
			}
		});

		// ***** Recording Audio Function
		record_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (recordActive == 0) {
					recordActive = 1;
					// Audio Recording
					// store it to sd card
					record_button.setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.ic_audiostoprecord, 0, 0);

					outputFile = Environment.getExternalStorageDirectory()
							.getAbsolutePath()
							+ "/"
							+ getAudiorecording().toString() + ".mp4";
					AudioMainPath = Environment.getExternalStorageDirectory()
							.getAbsolutePath() + "/";
					currentAudioName = getAudiorecording().toString() + ".mp4";
					myRecorder = new MediaRecorder();
					myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
					myRecorder
							.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
					myRecorder
							.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
					myRecorder.setOutputFile(outputFile);
					Log.v(TAG, "AUDIO PATH : " + currentAudioName);
					saveMediaFileDetails();
					play_button.setEnabled(false);
					start(view);
				} else if (recordActive == 1) {
					recordActive = 0;
					record_button.setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.ic_audiorecord, 0, 0);
					play_button.setEnabled(true);
					stop(view);
				}

			}
		});

		// Play Current Recoring
		play_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (recordPlay == 0) {
					recordPlay = 1;
					/*
					 * play_button.setBackground(getResources().getDrawable(
					 * R.drawable.playstop_button));
					 */
					play_button.setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.ic_pausemedia, 0, 0);
					record_button.setEnabled(false);
					recordPlay(view);
				} else if (recordPlay == 1) {
					recordPlay = 0;
					/*
					 * play_button.setBackground(getResources().getDrawable(
					 * R.drawable.play_button));
					 */
					play_button.setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.ic_playmedia, 0, 0);
					record_button.setEnabled(true);
					stopPlay(view);
				}

			}
		});

		// Launch Camera
		ivThumbnailPhoto = (ImageView) findViewById(R.id.ImageView01);
		camera_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// create intent with ACTION_IMAGE_CAPTURE action
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
						ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

				Log.v(TAG, "PRINT _ 1: " + fileUri);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
				// start the image capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
			}
		});

		gallery_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
					Intent intent = new Intent();
					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(
							Intent.createChooser(intent, "Select Picture"),
							PICK_IMAGE);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}

			}
		});

		audio_gallery_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {

					Intent intent = new Intent();
					intent.setType("audio/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(
							Intent.createChooser(intent, "Select Audio "),
							SELECT_AUDIO);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}
				// openGalleryAudio();
			}
		});

		video_gallery_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {

					Intent intent = new Intent();
					intent.setType("video/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(
							Intent.createChooser(intent, "Select Video "),
							SELECT_VIDEO);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}

			}
		});

		videorecord_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
						ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
				String URIPATH = fileUri.toString();
				String[] separated = URIPATH.split("/");
				currentVideoName = separated[8];
				Log.v(TAG, "VIDEO PRINT URI : " + currentVideoName);
				// file:///storage/emulated/0/Pictures/lANGUAGEAPP/VID_20140421_133732.mp4
				// set video quality
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the
																	// image
																	// file
																	// name
				openPath(fileUri);

				videoPreview.setVisibility(View.VISIBLE);
				// start the video capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
			}
		});

		// Play Current Video Recoring
		videorecordplay_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View view) {
				camvideoparent.setVisibility(View.VISIBLE);
				if (fileUri == null) {
					Toast.makeText(LanguageAppCaptureModify.this, "No Video",
							Toast.LENGTH_LONG).show();
				} else {
					if (recordPlayVideo == 0) {
						/*
						 * Toast.makeText(LanguageAppCaptureActivity.this,
						 * "Playback: " + fileUri.getPath(),
						 * Toast.LENGTH_LONG).show();
						 */
						recordPlayVideo = 1;
						videorecordplay_button
								.setCompoundDrawablesWithIntrinsicBounds(0,
										R.drawable.ic_pausemedia, 0, 0);
						videorecord_button.setEnabled(false);
						videoPreview.setVideoURI(fileUri);
						videoPreview.start();
					} else if (recordPlayVideo == 1) {
						recordPlayVideo = 0;
						videorecordplay_button
								.setCompoundDrawablesWithIntrinsicBounds(0,
										R.drawable.ic_playmedia, 0, 0);
						videorecord_button.setEnabled(true);
						stopPlayVideo(view);
					}
					videoPreview
							.setOnCompletionListener(new OnCompletionListener() {

								public void onCompletion(MediaPlayer mp) {
									stopPlayVideo(view);
									recordPlayVideo = 0;
									videorecordplay_button
											.setCompoundDrawablesWithIntrinsicBounds(
													0, R.drawable.ic_playmedia,
													0, 0);
									videorecord_button.setEnabled(true);
									Log.e("########", "Video Play Completed...");
								}
							});
				}
			}
		});
		// Video recording Function gallery_button,audiorecord_button

	
		
		loadTypeOfCapture();
		loadCategory();

		// Spinner List Handling Activities
		spinnerTypeOfCapture.setAdapter(m_adapterForSpinnerTC);
		spinnerTypeOfCapture
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						CurrentTypeOfCapture = spinnerTypeOfCapture
								.getSelectedItem().toString();
						if (!(CurrentTypeOfCapture.equals("SELECT SERVER DB"))) {

							mydb = openOrCreateDatabase(DATABASE_NAME,
									Context.MODE_PRIVATE, null);

							Cursor getfromloccur = null;
							try {
								getfromloccur = mydb.query(CONTENTTYPE_TABLE,
										null, "content='"
												+ CurrentTypeOfCapture + "'",
										null, null, null, null, null);
							} catch (Exception e) {

							}
							if (getfromloccur != null) {
								if (getfromloccur.getCount() > 0) {
									while (getfromloccur.moveToNext()) {
										content_type_id = getfromloccur
												.getString(1);
										type = getfromloccur.getString(2);
										if (type.equals("Word")) {
											capturewordblock
													.setVisibility(LinearLayout.VISIBLE);
											capturephraseblock
													.setVisibility(LinearLayout.GONE);
											capturestoryblock
													.setVisibility(LinearLayout.GONE);
											captureidiomblock
													.setVisibility(LinearLayout.GONE);
											capturesongsblock
													.setVisibility(LinearLayout.GONE);
										} else if (type.equals("Phrase")) {
											capturephraseblock
													.setVisibility(LinearLayout.VISIBLE);
											capturewordblock
													.setVisibility(LinearLayout.GONE);
											capturestoryblock
													.setVisibility(LinearLayout.GONE);
											captureidiomblock
													.setVisibility(LinearLayout.GONE);
											capturesongsblock
													.setVisibility(LinearLayout.GONE);
										} else if (type.equals("Story")) {
											capturestoryblock
													.setVisibility(LinearLayout.VISIBLE);
											capturewordblock
													.setVisibility(LinearLayout.GONE);
											capturephraseblock
													.setVisibility(LinearLayout.GONE);
											captureidiomblock
													.setVisibility(LinearLayout.GONE);
											capturesongsblock
													.setVisibility(LinearLayout.GONE);
										} else if (type.equals("Idiom")) {
											captureidiomblock
													.setVisibility(LinearLayout.VISIBLE);
											capturestoryblock
													.setVisibility(LinearLayout.GONE);
											capturewordblock
													.setVisibility(LinearLayout.GONE);
											capturephraseblock
													.setVisibility(LinearLayout.GONE);
											capturesongsblock
													.setVisibility(LinearLayout.GONE);
										} else if (type.equals("Song")) {
											capturesongsblock
													.setVisibility(LinearLayout.VISIBLE);
											captureidiomblock
													.setVisibility(LinearLayout.GONE);
											capturestoryblock
													.setVisibility(LinearLayout.GONE);
											capturewordblock
													.setVisibility(LinearLayout.GONE);
											capturephraseblock
													.setVisibility(LinearLayout.GONE);
										}

										Log.v(TAG, "Capture :"
												+ content_type_id + " = "
												+ type);
									}
								}
								getfromloccur.close();
							}

						} else {
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		spinnerCategory.setAdapter(m_adapterForSpinnerCat);
		spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				CurrentCategory = spinnerCategory.getSelectedItem().toString();
				if (!(CurrentCategory.equals("SELECT SERVER DB"))) {

					SQLiteDatabase mydb;
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);

					Cursor getFromCategory = null;
					try {
						getFromCategory = mydb.query(NODECATEGORY_TABLE, null,
								"node_category='" + CurrentCategory + "'",
								null, null, null, null, null);
					} catch (Exception e) {

					}
					if (getFromCategory != null) {
						if (getFromCategory.getCount() > 0) {
							while (getFromCategory.moveToNext()) {
								node_category_id = getFromCategory.getString(1);
								node_category = getFromCategory.getString(2);
								Log.v(TAG, "Category :" + node_category_id
										+ " = " + node_category);
							}
						}
						else{
							Log.v(TAG, "Category Not Excisting");
						}
						getFromCategory.close();
					}
					else{
						Log.v(TAG, "Category Not Excisting");
					}
				} else {
				}

			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

	}


	protected void openGalleryAudio() {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.setType("audio/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Audio "),
				SELECT_AUDIO);
	}

	protected void openGalleryVideo() {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.setType("video/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Video "),
				SELECT_VIDEO);
	}

	private void getCurrentUserDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor device_user = null;
		try {
			String query = "SELECT * FROM User";
			device_user = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}

		if (device_user != null) {
			if (device_user.getCount() > 0) {
				while (device_user.moveToNext()) {
					CurrentUID = device_user.getString(11);
				}
			}
		}
	}

	protected void saveMediaFileDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterFileUrl = new ContentValues();
		// Check Previous Language
		Cursor enterFileUrlDetails = null;
		try {
			enterFileUrlDetails = mydb.query(MEDIA_FILE_URL, null,
					"UploadingState !='0'", null, null, null, null);
		} catch (Exception e) {
		}
		if (enterFileUrlDetails != null) {
			if (enterFileUrlDetails.getCount() >= 1) {
				Log.v(TAG, "Excisting Language");
			} else {
				enterFileUrl.put("McategoryId", currentAudioName);
				enterFileUrl.put("MediaFileName", currentAudioName);
				enterFileUrl.put("ResouceDeviceUrl", AudioMainPath);
				enterFileUrl.put("ResouceServerUrl", AudioMainPath);
				enterFileUrl.put("UploadingState", "0");

				mydb.insert(MEDIA_FILE_URL, null, enterFileUrl);
				enterFileUrlDetails.close();
				mydb.close();
			}
		}

	}

	protected void stopPlayVideo(View view) {
		// TODO Auto-generated method stub
		videoPreview.pause();
	}

	public void onRadioButtonClicked(View view) {
		// Is the button now checked?
		boolean checked = ((RadioButton) view).isChecked();
		Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setText("RADIO CLICK :" + checked);
		toast.show();
	}

	private void loadCategory() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerCat = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerCat
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curNodeCategory = null;
		try {
			curNodeCategory = mydb.query(NODECATEGORY_TABLE, null, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (curNodeCategory != null) {
			if (curNodeCategory.getCount() > 0) {
				m_adapterForSpinnerCat.add(node_category);
				while (curNodeCategory.moveToNext()) {
					m_adapterForSpinnerCat.add(curNodeCategory.getString(2));
				}
			}
			else{
				Log.v("TAG", "CATEGORY EMPTY 1");
			}
			curNodeCategory.close();
		}
		else{
			Log.v("TAG", "CATEGORY NULL 1");
		}
		mydb.close();
	}

	private void loadTypeOfCapture() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerTC = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerTC
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curContentType = null;
		try {
			curContentType = mydb.query(CONTENTTYPE_TABLE, null, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (curContentType != null) {
			if (curContentType.getCount() > 0) {
				m_adapterForSpinnerTC.add(type);
				while (curContentType.moveToNext()) {
					m_adapterForSpinnerTC.add(curContentType.getString(2));
				}
			}
			curContentType.close();
		}
		mydb.close();
	}

	protected void stopPlay(View view) {
		// TODO Auto-generated method stub
		try {
			if (myPlayer != null) {
				myPlayer.stop();
				myPlayer.release();
				myPlayer = null;
				/*
				 * Toast.makeText(getApplicationContext(),
				 * "Stop playing the recording...", Toast.LENGTH_SHORT) .show();
				 */
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// Play Current Audio
	protected void recordPlay(final View view) {
		// TODO Auto-generated method stub
		try {
			myPlayer = new MediaPlayer();
			myPlayer.setDataSource(outputFile);
			myPlayer.prepare();
			myPlayer.start();
			Log.e("########", "Audio Recording Play Start...");
			// Audio Complete Identification
			myPlayer.setOnCompletionListener(new OnCompletionListener() {

				public void onCompletion(MediaPlayer mp) {
					stopPlay(view);
					recordPlay = 0;
					play_button.setCompoundDrawablesWithIntrinsicBounds(0,
							R.drawable.ic_playmedia, 0, 0);
					record_button.setEnabled(true);
					Log.e("########", "Audio Play Completed...");
				}
			});

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// Stop Playing Audio
	protected void stop(View view) {
		// TODO Auto-generated method stub
		try {
			myRecorder.stop();
			myRecorder.release();
			myRecorder = null;
			Log.e("########", "Audio Recording Play Stop...");
		} catch (IllegalStateException e) {
			// it is called before start()
			e.printStackTrace();
		} catch (RuntimeException e) {
			// no valid audio/video data has been received
			e.printStackTrace();
		}
	}

	// Start Playing Audio
	protected void start(View view) {
		// TODO Auto-generated method stub
		try {
			myRecorder.prepare();
			myRecorder.start();
			/*
			 * Toast.makeText(getApplicationContext(), "Start recording...",
			 * Toast.LENGTH_SHORT).show();
			 */
		} catch (IllegalStateException e) {
			// start:it is called before prepare()
			// prepare: it is called after start() or before setOutputFormat()
			e.printStackTrace();
		} catch (IOException e) {
			// prepare() fails
			e.printStackTrace();
		}

		/*
		 * startBtn.setEnabled(false); stopBtn.setEnabled(true);
		 */
	}

	protected void displayCancelDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(
				LanguageAppCaptureModify.this);
		builder.setTitle("CANCEL");
		builder.setMessage("Are Sure You Want To Exit...");
		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(getBaseContext(),
						Maori_MainActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});
		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(),
						"Add New Words Details..", Toast.LENGTH_LONG).show();
			}
		});
		builder.show();
	}

	// ****Data uploading background service
	private class UploadingNodeMediaDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					LanguageAppCaptureModify.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Media Details");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/saveNodeMediaDetails.php");
				JSONObject json = new JSONObject();

				json.put("record1", UpdatingNodeID);
			
				if (filename.equals("404")) {
					json.put("record2", "1=" + filename);
				} else {
					json.put("record2", "1="
							+ "http://langapp.mirzabros.com/lanappimage/"
							+ filename);
				}
				// uploading audio name
				if (currentAudioName.equals("202")) {
					json.put("record3", "2=" + currentAudioName);
				} else {
					json.put("record3", "2="
							+ "http://langapp.mirzabros.com/lanappaudio/"
							+ currentAudioName);
				}
				// uploading video name
				if (currentVideoName.equals("303")) {
					json.put("record4", "3=" + currentVideoName);
				} else {
					json.put("record4", "3="
							+ "http://langapp.mirzabros.com/lanappvideo/"
							+ currentVideoName);
				}
				json.put("record5", CurrentUID);
				
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			//mProgressDialog.dismiss();

			if (isNetworkAvailable()) {
				new UploadTask().execute();

			} else {
				AlertDialog.Builder b = new AlertDialog.Builder(
						LanguageAppCaptureModify.this);
				b.setMessage("Internet connectivity failure.Try again!");
				b.show();
			}

		}

	}

	// ****Data uploading background service
	private class UploadingWordsDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					LanguageAppCaptureModify.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading " + type + " Details");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				if (type.equals("Word")) {
					CurrentContentType = "1";
					if (ACTIVE.equals("1")) {
						saveUploadingWordDetails(); // Reuse For Existing Search
					}
					httppost = new HttpPost(saveWordDetailsUrl);
				} else if (type.equals("Phrase")) {
					CurrentContentType = "2";
					if (ACTIVE.equals("1")) {
						saveUploadingPhraseDetails();
					}
					httppost = new HttpPost(savePhraseDetailsUrl);
				} else if (type.equals("Story")) {
					if (ACTIVE.equals("1")) {
						saveUploadingStoryDetails();
					}
					CurrentContentType = "3";
					httppost = new HttpPost(saveStoryDetailsUrl);
				} else if (type.equals("Idiom")) {
					CurrentContentType = "5";
					if (ACTIVE.equals("1")) {
						saveUploadingIdiomDetails();
					}
					httppost = new HttpPost(saveIdiomDetailsUrl);
				} else if (type.equals("Song")) {
					CurrentContentType = "4";
					if (ACTIVE.equals("1")) {
						saveUploadingSongsDetails();
					}
					httppost = new HttpPost(saveSongDetailsUrl);

				}
				Log.v(TAG, "Curate Modify UID : " + CurrentUID);
				Log.v(TAG, "Curate Modify NID : " + UpdatingNodeID);
				JSONObject json = new JSONObject();
				// Selected Type ID
				json.put("record0", UpdatingNodeID);
				// Selected Type ID
				json.put("record1", CurrentContentType);
				// Added User ID
				json.put("record2", CurrentUID);
				// Record Added Date
				json.put("record3", getAddDateTimeString().toString());
				// Uploading user id
				json.put("record4", CurrentUID);
				// Record Updated
				json.put("record5", getAddDateTimeString().toString());
				// Selected dialect ID
				json.put("record6", SelectedDialect);
				// Curent Node Category ID
				json.put("record7", CATEGORYID);
				// Uploading Language Details
				json.put("record8", "2=1"); // LID

				if (type.equals("Word")) {
					// Uploading Word Details
					json.put("record9", etenglishword.getText().toString()
							+ "=" + etmaoriword.getText().toString()); // word
				} else if (type.equals("Phrase")) {
					// Uploading Phrase Details
					json.put("record9", etenglishphrase.getText().toString()
							+ "=" + etmaoriphrase.getText().toString()); // word
				} else if (type.equals("Idiom")) {
					// Uploading Idiom Details
					json.put("record9", etenglishidiom.getText().toString()
							+ "=" + etmaoriidiom.getText().toString()); // word
				} else if (type.equals("Song")) {
					// etmaorisongstitle,etmaorisongscontent,etenglishsongstitle,etenglishsongscontent
					json.put("recordt9", etenglishsongstitle.getText()
							.toString()
							+ "="
							+ etmaorisongstitle.getText().toString()); // word
					json.put("record9", etenglishsongscontent.getText()
							.toString()
							+ "="
							+ etmaorisongscontent.getText().toString()); // word
					Log.v(TAG, "SAVE SONGS");
				} else if (type.equals("Story")) {
					// etmaoristorytitle/etmaoristorycontent/etenglishstorytitle/etenglishstorycontent
					json.put("recordt9", etenglishstorytitle.getText()
							.toString()
							+ "="
							+ etmaoristorytitle.getText().toString()); // word
					json.put("record9", etenglishstorycontent.getText()
							.toString()
							+ "="
							+ etmaoristorycontent.getText().toString()); // word
					Log.v(TAG, "SAVE STORY");
				}
				/*
				 * String currentAudioName = "202"; String currentVideoName =
				 * "303"; static String filename = "404";
				 */
				// uploading image name
				if (filename.equals("404")) {
					json.put("record10", "1=" + filename);
				} else {
					json.put("record10", "1="
							+ "http://langapp.mirzabros.com/lanappimage/"
							+ filename);
				}
				// uploading audio name
				if (currentAudioName.equals("202")) {
					json.put("record11", "2=" + currentAudioName);
				} else {
					json.put("record11", "2="
							+ "http://langapp.mirzabros.com/lanappaudio/"
							+ currentAudioName);
				}
				// uploading video name
				if (currentVideoName.equals("303")) {
					json.put("record12", "3=" + currentVideoName);
				} else {
					json.put("record12", "3="
							+ "http://langapp.mirzabros.com/lanappvideo/"
							+ currentVideoName);
				}
				// Uploading url details
				json.put("record13", etvideourl.getText().toString());
				json.put("record14", "6");
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			
			if (result != null) {
				arraylist = new ArrayList<HashMap<String, String>>();
				try {
					JSONObject jsonObj = new JSONObject(result);
					jsonarray = jsonObj.getJSONArray("posts");
					for (int i = 0; i < jsonarray.length(); i++) {
						JSONObject c = jsonarray.getJSONObject(i);
						HashMap<String, String> map = new HashMap<String, String>();
					    String CurrentNodeID =  c.getString("InsertedNID");
					    
						if (type.equals("Word")) {
							mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
							try {
								ContentValues add_update_node = new ContentValues();
								add_update_node.put("WordID", CurrentNodeID);
								add_update_node.put("NID", CurrentNodeID);
								mydb.update(WORD_TABLE, add_update_node, "NID = '9999'", null);
							}
							catch(Exception e){
								
							}
							mydb.close();
						}
						else if (type.equals("Phrase")) {
							mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
							try {
								ContentValues add_update_node = new ContentValues();
								add_update_node.put("PhraseID", CurrentNodeID);
								add_update_node.put("NID", CurrentNodeID);
								mydb.update(PHRASE_TABLE, add_update_node, "NID = '9999'", null);
							}
							catch(Exception e){
								
							}
							mydb.close();
							
						}
						else if (type.equals("Idiom")) {
							
							mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
							try {
								ContentValues add_update_node = new ContentValues();
								add_update_node.put("IdiomID", CurrentNodeID);
								add_update_node.put("NID", CurrentNodeID);
								mydb.update(IDIOM_TABLE, add_update_node, "NID = '9999'", null);
							}
							catch(Exception e){
								
							}
							mydb.close();
							 
						}
						else if (type.equals("Song")) {
							mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
							try {
								ContentValues add_update_node = new ContentValues();
								add_update_node.put("SongID", CurrentNodeID);
								add_update_node.put("NID", CurrentNodeID);
								mydb.update(SONG_TABLE, add_update_node, "NID = '9999'", null);
							}
							catch(Exception e){
								
							}
							mydb.close();
						}
						else if (type.equals("Story")) {
							mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
							try {
								ContentValues add_update_node = new ContentValues();
								add_update_node.put("StoryID", CurrentNodeID);
								add_update_node.put("NID", CurrentNodeID);
								mydb.update(STORY_TABLE, add_update_node, "NID = '9999'", null);
							}
							catch(Exception e){
								
							}
							mydb.close();
						}
					}
				}
				catch(Exception e){
					
				}
			}
			
			
			
			if (isNetworkAvailable()) {
				new UploadTask().execute();

			} else {
				AlertDialog.Builder b = new AlertDialog.Builder(
						LanguageAppCaptureModify.this);
				b.setMessage("Internet connectivity failure.Try again!");
				b.show();
			}

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void saveUploadingSongsDetails() {
		// TODO Auto-generated method stub
		Log.v(TAG, "saveUploadingSongsDetails"
				+ etmaoristorytitle.getText().toString());
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterWordInfo = new ContentValues();
		try {
			enterWordInfo.put("SongID", "9999");
			enterWordInfo.put("LID", "1-2");
			enterWordInfo.put("NID", "9999");
			enterWordInfo.put("song_title", etmaorisongstitle.getText()
					.toString());
			enterWordInfo.put("song_content", etmaorisongscontent.getText()
					.toString());
			enterWordInfo.put("other_song_title", etenglishsongstitle.getText()
					.toString());
			enterWordInfo.put("other_song_content", etenglishsongscontent
					.getText().toString());
			mydb.insert(SONG_TABLE, null, enterWordInfo);
		} catch (Exception e) {
		}
		mydb.close();
	}

	public void saveUploadingIdiomDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterWordInfo = new ContentValues();
		try {
			enterWordInfo.put("IdiomID", "9999");
			enterWordInfo.put("LID", "1-2");
			enterWordInfo.put("NID", "9999");
			enterWordInfo.put("Idiom", etmaoriidiom.getText().toString());
			enterWordInfo.put("Otheridioms", etenglishidiom.getText()
					.toString());
			mydb.insert(IDIOM_TABLE, null, enterWordInfo);
		} catch (Exception e) {
		}
		mydb.close();
	}

	public void saveUploadingStoryDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterWordInfo = new ContentValues();
		try {
			enterWordInfo.put("StoryID", "9999");
			enterWordInfo.put("LID", "1-2");
			enterWordInfo.put("NID", "9999");
			enterWordInfo.put("story_title", etmaoristorytitle.getText()
					.toString());
			enterWordInfo.put("story_content", etmaoristorycontent.getText()
					.toString());
			enterWordInfo.put("other_story_title", etenglishstorytitle
					.getText().toString());
			enterWordInfo.put("other_story_content", etenglishstorycontent
					.getText().toString());
			mydb.insert(STORY_TABLE, null, enterWordInfo);
		} catch (Exception e) {
		}
		mydb.close();
	}

	public void saveUploadingPhraseDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterWordInfo = new ContentValues();
		try {
			enterWordInfo.put("PhraseID", "9999");
			enterWordInfo.put("LID", "1-2");
			enterWordInfo.put("NID", "9999");
			enterWordInfo.put("Phrase", etmaoriphrase.getText().toString());
			enterWordInfo.put("OtherPhrase", etenglishphrase.getText()
					.toString());
			mydb.insert(PHRASE_TABLE, null, enterWordInfo);
		} catch (Exception e) {
		}
		mydb.close();
	}

	public void saveUploadingWordDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterWordInfo = new ContentValues();
		try {
			enterWordInfo.put("WordID", "9999");
			enterWordInfo.put("LID", "1-2");
			enterWordInfo.put("NID", "9999");
			enterWordInfo.put("word", etmaoriword.getText().toString());
			enterWordInfo.put("Otherwords", etenglishword.getText().toString());
			mydb.insert(WORD_TABLE, null, enterWordInfo);
		} catch (Exception e) {
		}
		mydb.close();
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getAudiorecording() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	/**
	 * Receiving activity result method will be called after closing the camera
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if the result is capturing Image
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// successfully captured the image
				// display it in image view
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				Toast.makeText(getApplicationContext(),
						"User cancelled image capture", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to capture image
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
						.show();
			}
		} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
			camvideoparent.setVisibility(View.VISIBLE);
			if (resultCode == RESULT_OK) {
				// video successfully recorded
				// preview the recorded video
				camvideoparent.setVisibility(View.VISIBLE);
				previewVideo();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled recording
				Toast.makeText(getApplicationContext(),
						"User cancelled video recording", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to record video
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to record video", Toast.LENGTH_SHORT)
						.show();
			}
		}

		else if (resultCode == Activity.RESULT_OK) {
			if (requestCode == PICK_IMAGE) {
				selectedImageUri = data.getData();
				Log.e("Bitmap", "selectedImageUri :" + selectedImageUri);
				try {
					// OI FILE Manager
					filemanagerstring = selectedImageUri.getPath();
					Log.e("TAG", "IMAGE PATH  100:" + filemanagerstring);
					// MEDIA GALLERY
					selectedImagePath = getPath(selectedImageUri);
					Log.e("TAG", "IMAGE PATH  200:" + selectedImagePath);
					if (selectedImagePath != null) {
						filePath = selectedImagePath;
					} else if (filemanagerstring != null) {
						filePath = filemanagerstring;
					} else {
						Toast.makeText(getApplicationContext(), "Unknown path",
								Toast.LENGTH_LONG).show();
						Log.e("Bitmap", "Unknown Path");
					}
					if (filePath != null) {
						decodeFile(filePath);
					} else {
						bitmap = null;
					}
					String[] projection = { MediaStore.MediaColumns.DISPLAY_NAME };
					ContentResolver cr = getApplicationContext()
							.getContentResolver();
					Cursor metaCursor = cr.query(selectedImageUri, projection,
							null, null, null);
					if (metaCursor != null) {
						try {
							if (metaCursor.moveToFirst()) {
								filename = metaCursor.getString(0);
								Log.v(TAG, "Image NAME 9999: " + filename);
								upladingFromPath = filePath.replace(
										filename.trim(), "");
								Log.v(TAG, "Image NAME Path 9999: "
										+ upladingFromPathAudio);
							}
						} finally {
							metaCursor.close();
						}
					}
					upladingFromPath = filePath.replace(filename.trim(), "");
					filename = filename.trim();

					Log.e("TAG", "IMAGE PATH  199:" + upladingFromPath);
					Log.e("TAG", "IMAGE PATH  299:" + filename);
					Log.e("TAG", "IMAGE PATH  300:" + filePath + " = "
							+ upladingFromPath);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Internal error",
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}
			}

			else if (requestCode == SELECT_AUDIO) {

				try {
					Uri selectedImageUri = data.getData();
					selectedPath = getPath(selectedImageUri);
					outputFile = getPath(selectedImageUri);

					String[] projection = { MediaStore.MediaColumns.DISPLAY_NAME };
					ContentResolver cr = getApplicationContext()
							.getContentResolver();
					Cursor metaCursor = cr.query(selectedImageUri, projection,
							null, null, null);
					if (metaCursor != null) {
						try {
							if (metaCursor.moveToFirst()) {
								currentAudioName = metaCursor.getString(0);
								Log.v(TAG, "AUDIO NAME : " + currentAudioName);
								upladingFromPathAudio = selectedPath.replace(
										currentAudioName.trim(), "");
								Log.v(TAG, "AUDIO NAME File Path : "
										+ upladingFromPathAudio);
							}
						} finally {
							metaCursor.close();
						}
					}

				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Log.v("TAG", "AUDIO GALLERY PATH :" + selectedPath);
				// System.out.println("SELECT_AUDIO Path : " + selectedPath);

			} else if (requestCode == SELECT_VIDEO) {

				try {
					Uri selectedImageUri = data.getData();
					fileUri = data.getData();
					selectedPath = getPath(selectedImageUri);
					outputFile = getPath(selectedImageUri);
					Log.v(TAG, "VIDEO PATH : " + selectedPath);
					String[] projection = { MediaStore.MediaColumns.DISPLAY_NAME };
					ContentResolver cr = getApplicationContext()
							.getContentResolver();
					Cursor metaCursor = cr.query(selectedImageUri, projection,
							null, null, null);
					if (metaCursor != null) {
						try {
							if (metaCursor.moveToFirst()) {
								currentVideoName = metaCursor.getString(0);
								upladingFromPathVideo = selectedPath.replace(
										currentVideoName.trim(), "");
							}
						} finally {
							metaCursor.close();
						}
					}
					Log.v(TAG, "VIDEO NAME : " + currentVideoName);
					Log.v(TAG, "VIDEO PATH : " + upladingFromPathVideo);

				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	private boolean prepareDirectory() {
		try {
			if (makedirs()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(
					this,
					"Could not initiate File System.. Is Sdcard mounted properly?",
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	private boolean makedirs() {
		File tempdir = new File(tempDir);
		if (!tempdir.exists())
			tempdir.mkdirs();

		if (tempdir.isDirectory()) {

		}
		return (tempdir.isDirectory());
	}

	private String decodeFile(String filePath) {
		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, o);

		// The new size we want to scale to
		final int REQUIRED_SIZE = 512;

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
				break;
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;

		bitmap = BitmapFactory.decodeFile(filePath, o2);
		ivThumbnailPhoto.setImageBitmap(bitmap);

		Calendar c = Calendar.getInstance();
		SimpleDateFormat dfsigdate = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedSigDatep = dfsigdate.format(c.getTime());
		tempDir = "/data/data/com.maori.languageapp/CAMIMAGES/";
		prepareDirectory();
		String filenamepath = tempDir + getAudiorecording().toString() + ".png";
		filename = getAudiorecording().toString() + ".png";
		Log.v(TAG, "XXX Img Name : " + filename);
		Log.v(TAG, "XXX tempDir : " + filenamepath);
		File dest = new File(filenamepath);
		try {
			FileOutputStream out = new FileOutputStream(dest);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			Log.v(TAG, "Exception : " + e);
		}

		return filePath;
	}

	private String getPath(Uri selectedImageUri) throws FileNotFoundException {

		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
				null);

		if (cursor != null) {

			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

			cursor.moveToFirst();
			/* Uri uri = Uri.parse(cursor.getString(1)); */

			return cursor.getString(column_index);
		} else
			return null;
	}

	// ====================================
	private byte[] getByteArrayFromImage(String filePath)
			throws FileNotFoundException, IOException {

		File file = new File(filePath);
		System.out.println(file.exists() + "!!");

		FileInputStream fis = new FileInputStream(file);
		// create FileInputStream which obtains input bytes from a file in a
		// file system
		// FileInputStream is meant for reading streams of raw bytes such as
		// image data. For reading streams of characters, consider using
		// FileReader.

		// InputStream in = resource.openStream();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		try {
			for (int readNum; (readNum = fis.read(buf)) != -1;) {
				bos.write(buf, 0, readNum);
				// no doubt here is 0
				/*
				 * Writes len bytes from the specified byte array starting at
				 * offset off to this byte array output stream.
				 */
				System.out.println("read " + readNum + " bytes,");
			}
		} catch (IOException ex) {
			Log.d("error", "error");
		}
		byte[] bytes = bos.toByteArray();
		return bytes;
	}

	/**
	 * ------------ Helper Methods ----------------------
	 * */

	public void openPath(Uri uri) {
		InputStream is = null;
		try {
			is = getContentResolver().openInputStream(uri);

			// Convert your stream to data here
			is.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);
		Log.v(TAG, "PRINT _ 4: " + mediaStorageDir);
		upladingFromPath = mediaStorageDir.getAbsolutePath();
		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
			filename = "IMG_" + timeStamp + ".jpg";
			sourceUrl = mediaFile.toString();
			Log.v(TAG, "PRINT _ 5: " + filename);
			Log.v(TAG, "PRINT _ 6: " + sourceUrl);

		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
			Log.v(TAG, "PRINT _ 7: " + mediaFile);
		} else {
			return null;
		}

		return mediaFile;
	}

	/*
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {
			// hide video preview
			// videoPreview.setVisibility(View.GONE);

			ivThumbnailPhoto.setVisibility(View.VISIBLE);

			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();

			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;

			final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
					options);
			ivThumbnailPhoto.setImageBitmap(bitmap);
			Log.v(TAG, "PRINT _ PREVIEW 1 : " + fileUri.getPath());

		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	/*
	 * Previewing recorded video
	 */
	private void previewVideo() {
		try {
			camvideoparent.setVisibility(View.VISIBLE);
			videoPreview.setVideoPath(fileUri.getPath());
			// start playing
			// videoPreview.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// *********Media Files Uploading **************

	// ******UPLOADING BLOCK************************
	// Check Internet Connection!!!

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	class UploadTask extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			/*pDialog = new ProgressDialog(LanguageAppCaptureActivity.this);
			pDialog.setMessage("Uploading Image Files...");
			pDialog.show();*/
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP

			Log.v(TAG, "UPLOAD IMAGE 1 : " + upladingFromPath);
			Log.v(TAG, "UPLOAD IMAGE 2 : " + filename);
			Log.v(TAG, "UPLOAD IMAGE 3 : " + desDirectory);

			uploadStat = new UploadToFtp().ftpUpload1(upladingFromPath,
					filename, desDirectory);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (uploadStat) {
						Log.v("TAG","Image Upload Success.");
					} else {
						/*AlertDialog.Builder b = new AlertDialog.Builder(
								LanguageAppCaptureActivity.this);
						b.setMessage("Upload Failed.");
						b.show();*/
						Log.v("TAG","Image Upload Failed.");
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				//pDialog.dismiss();
			}
			super.onPostExecute(result);
			new UploadTaskAudio().execute();

		}
	}

	/**************** Uploading Audio Via FTP ************************/
	class UploadTaskAudio extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			/*pDialog = new ProgressDialog(LanguageAppCaptureActivity.this);
			pDialog.setMessage("Uploading Audio Files...");
			pDialog.show();*/
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			// AUDIO PATH GALEERY :
			// /storage/emulated/0/Ringtones/hangouts_video_call.ogg

			// upladingFromPathAudio = "/storage/emulated/0/";
			Log.v(TAG, "UPLOAD AUDIO 1 : " + upladingFromPathAudio);
			Log.v(TAG, "UPLOAD AUDIO 2 : " + currentAudioName);
			Log.v(TAG, "UPLOAD AUDIO 3 : " + desDirectory);

			uploadStat = new UploadToFtpAudio().ftpUpload1(
					upladingFromPathAudio, currentAudioName, desDirectory);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (uploadStat) {
						Log.v("TAG","Image Upload Success.");
					} else {
						Log.v("TAG","Image Upload Failed.");
						/*AlertDialog.Builder b = new AlertDialog.Builder(
								LanguageAppCaptureActivity.this);
						b.setMessage("Upload Failed.");
						b.show();*/
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				//pDialog.dismiss();
			}
			super.onPostExecute(result);
			new UploadTaskVideo().execute();
		}
	}

	/**************** Uploading Video Via FTP ************************/
	class UploadTaskVideo extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
		/*	pDialog = new ProgressDialog(LanguageAppCaptureActivity.this);
			pDialog.setMessage("Uploading Video Files...");
			pDialog.show();*/
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			Log.v(TAG, "UPLOAD VIDEO 1 : " + upladingFromPathVideo);
			Log.v(TAG, "UPLOAD VIDEO 2 : " + currentVideoName);
			Log.v(TAG, "UPLOAD VIDEO 3 : " + desDirectory);

			uploadStat = new UploadToFtpVideo().ftpUpload1(
					upladingFromPathVideo, currentVideoName, desDirectory);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (uploadStat) {
						Log.v("TAG","Image Upload Success.");
					} else {
						Log.v("TAG","Image Upload Failed.");
						/*AlertDialog.Builder b = new AlertDialog.Builder(
								LanguageAppCaptureActivity.this);
						b.setMessage("Upload Failed.");
						b.show();*/
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				//pDialog.dismiss();
			}
			
			if (null != mProgressDialog && mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
			}
			super.onPostExecute(result);
			
			
			final AlertDialog alertDialog = new AlertDialog.Builder(
					LanguageAppCaptureModify.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPLOAD COMPLETED");
			// Setting Dialog Message
			alertDialog.setMessage("Data Uploaded Successfully...");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					new UploadApprovalInformation().execute();
					Intent myIntent = new Intent(getBaseContext(),
							Maori_MainActivity.class);
					myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivityForResult(myIntent, 0);
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	// ***********Memory Handling****************
	@Override
	protected void onStop() {
		super.onStop();
	}

	// Fires after the OnStop() state
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			trimCache(this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void trimCache(Context context) {
		try {
			File dir = context.getCacheDir();
			if (dir != null && dir.isDirectory()) {
				deleteDir(dir);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static boolean deleteDir(File dir) {
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}
	
	
	// Display Network connection Fail Alert
		public void showAlertDialog(Context context, String title, String message,
				Boolean status) {
			final AlertDialog alertDialog = new AlertDialog.Builder(context)
					.create();

			// Setting Dialog Title
			alertDialog.setTitle(title);

			// Setting Dialog Message
			alertDialog.setMessage(message);

			// Setting alert dialog icon
			alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// new DownloadAdministrative().execute();
					alertDialog.dismiss();
				}
			});

			// Showing Alert Message
			alertDialog.show();
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
		}
		
		
		//*********Update curate states********************
		
		/*********************CURATE**********************/
		
		private class UploadApprovalInformation extends AsyncTask<Void, Void, Void> {
			private final String TAG = null;

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				try {
					HttpPost httppost = null;
					HttpConnectionParams.setConnectionTimeout(httpParameters,
							timeoutConnection);
					HttpClient httpclient = new DefaultHttpClient(httpParameters);
					JSONObject json = new JSONObject();
					httppost = new HttpPost(
							"http://langapp.mirzabros.com/maoriapi/curate/SaveCurateApprovalInfo.php");

					json.put("record1", CurrentUID); // $approve_user
					json.put("record2", "3"); // $approve_state
					json.put("record3", UpdatingNodeID); // $approve_node
					json.put("record4", "0"); // $approve_media
					json.put("record5", "0"); // $approve_media_id
		
					JSONArray postjson = new JSONArray();
					postjson.put(json);
					Log.v("TAG","POST MODIFY : " + postjson);
					httppost.setHeader("json", json.toString());
					httppost.getParams().setParameter("jsonpost", postjson);
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();
					is = entity.getContent();
					if (is != null) {

						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						is.close();
						result = sb.toString();
						Log.v("TAG", "Print RES ***:" + result);
						if (result != null) {

						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void args) {
				
			}
		}
		
}
